package com.easy.carl.algorithm.linkNode;

import com.easy.leetcode.ListNode;

/**
 * @ClassName MyLinkedList707
 * @Description 707. 设计链表
 * @Author zheng
 * @Date 2021/12/17 10:52
 * @Version 1.0
 **/
public class MyLinkedList707 {
    ListNode head = null;
    int count = 0;

    public MyLinkedList707() {
        head = new ListNode(-1);

    }

    public int get(int index) {
        ListNode cur = find(index);
        return cur == null ? -1 : cur.val;
    }

    public void addAtHead(int val) {
        ListNode next = head.next;
        head.next = new ListNode(val, next);
        count++;
    }

    public void addAtTail(int val) {
        ListNode tmp = head.next;
        ListNode pre = head;
        while (tmp != null) {
            pre = tmp;
            tmp = tmp.next;
        }
        pre.next = new ListNode(val);
        count++;
    }

    public void addAtIndex(int index, int val) {
        ListNode next = head.next;
        if (index < 0) {
            head.next = new ListNode(val, next);
            return;
        }
        ListNode pre = find(index - 1);
        if (pre != null) {
            count++;
            pre.next = new ListNode(val, pre.next);
        }
    }


    public void deleteAtIndex(int index) {
        if (index < count && index > -1) {
            ListNode pre = find(index - 1);
            ListNode cur = pre.next;
            if (cur != null) {
                pre.next = cur.next;
            }
        }
    }


    public ListNode find(int index) {
        if (index < -1 || index > count - 1) {
            return null;
        }
        int i = -1;
        ListNode current = head;
        while (i < index) {
            current = current.next;
            i++;
        }
        return current;
    }

    public static void main(String[] args) {
        MyLinkedList707 myLinkedList707 = new MyLinkedList707();
        myLinkedList707.addAtHead(2);
        myLinkedList707.addAtIndex(0, 1);
        System.out.println(myLinkedList707.get(1));
    }
}
